﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace MvcCarConsume.WebUI
{
    public class VMBase
    {
        public virtual string GetPropertyDisplayName(string propertyName)
        {
            var pro = this.GetType().GetProperty(propertyName);
            if (pro == null)
                return null;
            var attrDisplays = pro.GetCustomAttributes(typeof(DisplayAttribute),false);  //DisplayAttribute is sealed
            var attrDisplayNames = pro.GetCustomAttributes(typeof(DisplayNameAttribute), true);
            if (attrDisplayNames != null && attrDisplayNames.Length > 0)
            {
                var attrDisplayName = attrDisplayNames[0] as DisplayNameAttribute;
                return attrDisplayName.DisplayName;
            }
            else if (attrDisplays != null && attrDisplays.Length > 0)
            {
                var attrDisplay = attrDisplays[0] as DisplayAttribute;
                string value;
                try
                {
                    if (HttpContext.Current != null)
                        value = HttpContext.GetGlobalResourceObject(attrDisplay.ResourceType.Name, attrDisplay.Name).ToString();
                    else
                        value = attrDisplay.GetName();
                    if (value != null)
                        return value;
                    return propertyName;
                }
                catch{ return propertyName;}
            }
            else
            {
                return propertyName;
            }
        }
    }
}